package com.google.appengine.a4ieve.servlets.resources;

import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
import com.google.appengine.repackaged.com.google.common.util.Base64;
import org.json.JSONObject;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Logger;

class ImageDecoderServant implements Servant {

    private static final Logger LOG = Logger.getLogger(ImageDecoderServant.class.getName());
    private static final String QUERY_KEY = "query";
    private static final String CONTENT_TYPE = "Content-Type";

    @Override
    public void process(HttpServletRequest req, HttpServletResponse resp) {
        String imageQuery = req.getParameter(QUERY_KEY);
        try {
            URL url = new URL(imageQuery);
            URLConnection connection = url.openConnection();
            HTTPResponse response;

            response = URLFetchServiceFactory.getURLFetchService().fetch(url);

            byte[] image = response.getContent();
            String contentType = null;
            for (HTTPHeader header : response.getHeaders()) {
//            LOG.severe(header.getName() + " " + header.getValue());
                if (CONTENT_TYPE.equals(header.getName())) {
                    contentType = header.getValue();
                    break;
                }
            }
            String encoded = Base64.encode(image);
            MimetypesFileTypeMap mftp = new MimetypesFileTypeMap();
            mftp.addMimeTypes("image png tif jpg jpeg bmp");
            String mimeType = mftp.getContentType(encoded);
            LOG.severe("Mime type is " + mimeType);
            String contentPrefix = "data:" + (contentType == null ? mimeType : contentType) + ";base64,";

            JSONObject out = new JSONObject();
            out.put("image", contentPrefix + encoded);
            out.write(resp.getWriter());
        } catch (IOException e) {
            JSONObject err = new JSONObject();
            err.put("error", e.getMessage());
            try {
                err.write(resp.getWriter());
            } catch (IOException ex) {
                LOG.severe("Error while writing response" + ex);
            }
        }
    }
}
